<template>
    <el-card>
        <div class="search-query">
            <el-form :inline="true" :model="searchForm" ref="searchFormRef">
                <el-form-item label="字典类型名称" prop="typeName">
                    <el-input v-model="searchForm.typeName" placeholder="请输入字典类型名称" clearable />
                </el-form-item>
                <el-form-item label="字典类型编码" prop="typeCode">
                    <el-input v-model="searchForm.typeCode" placeholder="请输入字典类型编码" clearable />
                </el-form-item>
               
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleSearchReset(searchFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="table-btn">
            <el-space :size="10">
                <el-button type="primary" @click="handleAddView">新增</el-button>
                <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
            </el-space>

            <el-button type="primary" @click="handleReflesh">刷新</el-button>
        </div>

        <el-table border :data="dictData.list" v-loading="loading" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="typeName" label="字典类型名称" />
            <el-table-column prop="typeCode" label="字典类型编码" />
            <el-table-column prop="remark" label="备注" />
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.status === 0"> 正常</el-tag>
                    <el-tag v-else type="danger">停用</el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作">
                <template v-slot="scope" #default>
                    <el-button type="info" @click="handleDictData(scope.row)" link>字典项</el-button>
                    <el-button type="success" @click="handleEdit(scope.row)" link>编辑</el-button>
                    <el-button type="danger" @click="handleDelete(scope.row)" link>删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="dictData.currentPage" v-model:page-size="dictData.pageSize"
            :page-sizes="[10, 20, 50, 100]" background="background" layout="total, sizes, prev, pager, next,jumper"
            :total="dictData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑 -->
    <el-dialog v-model="visible" :title="addForm.id ? '编辑' : '新增'" width="500" :close-on-click-modal="false">
        <el-form :model="addForm" label-position="top" :rules="rules" ref="addFormRef">
            <el-form-item label="字典类型名称" prop="typeName">
                <el-input v-model="addForm.typeName" placeholder="请输入字典类型名称" clearable />
            </el-form-item>
            <el-form-item label="字典类型编码" prop="typeCode">
                <el-input v-model="addForm.typeCode" placeholder="请输入字典类型编码" clearable />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="addForm.remark" placeholder="备注" clearable />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="addForm.status" >
                    <el-radio :value="1">停用</el-radio>
                    <el-radio :value="0">正常</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <div>
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd(addFormRef)">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="js">

import { ref, onMounted } from 'vue'
import userOperationLog from '@/services/userOperationLog'
import dict from '@/services/dict'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'


const router = useRouter()
const loading = ref(false)
const dictData = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    list: []
})


const init = async () => {
    loading.value = true
    const res = await dict.page({})
    if (res.code == 200) {
        dictData.value = res.data
        loading.value = false
    }
}

onMounted(() => {
    init()
})

const handleDelete = async (row) => {
    const res = await dict.deleteByIds([row.id])
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: res.msg
        })
        init()
    }
}

let ids = []
const handleSelectionChange = (value) => {
    ids = []
    value.forEach(e => {
        ids.push(e.id)
    });
}

const handleBatchDelete = async () => {
    if (ids.length == 0) {
        throw ElMessage({
            type: 'warning',
            message: "请选择"
        })
    }
    const res = await dict.deleteByIds(ids)
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: res.msg
        })
        init()
    }
}

const handleReflesh = () => {
    init()
}

const searchFormRef = ref()
const searchForm = ref({
    typeName: '',
    typeCode: ''
})
// 搜素
const handleSearch = async () => {
    loading.value = true
    const res = await dict.page(searchForm.value)
    if (res.code === 200) {
        dictData.value = res.data
        loading.value = false
    }
}
// 搜索重置
const handleSearchReset = (formRef) => {
    formRef.resetFields()
}

// 当前页大小
const handleSizeChange = async (pageSize) => {
    loading.value = true
    const operateTime = searchForm.value.loginTime
    const data = {
        name: searchForm.value.name,
        loginTimeStart: '',
        loginTimeEnd: '',
        pageSize
    }

    if (operateTime?.length > 0) {
        data.startTime = operateTime[0]
        data.endTime = operateTime[1]
    }
    const res = await userOperationLog.page(data)
    if (res.code === 200) {
        userOperationLogData.value = res.data
        loading.value = false
    }
}

// 当前页数
const handleCurrentChange = async (currentPage) => {
    loading.value = true
    const operateTime = searchForm.value.loginTime
    const data = {
        name: searchForm.value.name,
        loginTimeStart: '',
        loginTimeEnd: '',
        currentPage
    }
    if (operateTime?.length > 0) {
        data.startTime = operateTime[0]
        data.endTime = operateTime[1]
    }
    const res = await userOperationLog.page(data)
    if (res.code === 200) {
        userOperationLogData.value = res.data
        loading.value = false
    }
}

const visible = ref(false)
// 新增弹窗
const handleAddView = () => {
    visible.value = true
    addForm.value = {}
}

const addFormRef = ref()
const addForm = ref({
    typeName: '',
    typeCode: '',
    status: 0,
    remark: ''
})

const rules = ref({
    typeName: [
        { required: true, message: '请输入字典类型名称', trigger: 'blur' },
    ],
    typeCode: [
        {
            required: true,
            message: '请输入字典类型编码',
            trigger: 'blur'
        }
    ],
    status: [
        {
            required: true,
            message: '请选择状态',
            trigger: 'change'
        }
    ]
})

// 新增
const handleAdd = async (formRef) => {
    if (!formRef) return
    await formRef.validate((valid, fields) => {
        if (valid) {
            dict.save(addForm.value).then((res) => {
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success'
                    })
                    init()
                }
            })

            visible.value = false
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 编辑
const handleEdit = (row) => {
    addForm.value = JSON.parse(JSON.stringify(row)) // 改过之后的
    visible.value = true
}

// 跳转到字典项
const handleDictData = (row) => {
    console.log(row)
    router.push('/system/dict/item')
}

</script>

<style lang="less" scoped>
.table-btn {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
}
</style>
